package com.minelx.datamicroscope.core.display;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.minelx.datamicroscope.core.query.ResourceMapping;

import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

public class DisplayTemplates {

	private final Map<String, DisplayTemplate> templates;

	public DisplayTemplates(Map<String, DisplayTemplate> templates) {
		this.templates = templates;
	}

	public void swap(List<ResourceMapping> files) {
		for (ResourceMapping file : files) {
			String resourceName = file.name();
			if (templates.containsKey(resourceName)) {
				templates.get(resourceName).process(file.resource().dataFrame());
			}
		}
	}

	public static DisplayTemplates from(JSONArray data) {
		return new DisplayTemplates(data.toJavaList(JSONObject.class).stream()
				.collect(toMap(
						jsonObject -> jsonObject.getString("resourceName"),
						jsonObject -> new DisplayTemplate(jsonObject.getJSONObject("operation")))));
	}

	public static DisplayTemplates empty() {
		return from(new JSONArray());
	}
}
